package local.xinshi.netmgr.pkg;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class BaseController {
    
    @Autowired
    SqlService sqlService;

    @Autowired
    ObjectMapper mapper;

    @Autowired
    SshService sshService;

    /**
     * web根路径
     */
    @RequestMapping("/")
    public String index(HttpSession session) {
        session.setAttribute("id", session.getId());
        if (session.getAttribute("login") == null) {
            return "index";
        }
        return "control";
    }

    /**
     * 登录验证，用户名或密码错误都转发到"/uerror"处理，成功则返回"control.html"视图
     */
    @PostMapping("/login")
    @ResponseBody
    public String login(HttpSession session,HttpServletRequest request) {
        if (session.getAttribute("login") == null) {
            String name = request.getParameter("name");
            String pwd = request.getParameter("pwd");
            if (name == null || pwd == null)
                return "用户名或密码不能为空";
            String role = sqlService.getUserRole(name, pwd);
            if (role == null)
                return "用户不存在";
            else if (role.equals(""))
                return "密码错误";
            session.setAttribute("role", role);
            session.setAttribute("login", name);
            UserSessions.put(name, session);
            String remoteIP = request.getHeader("X-Real-IP");
            sqlService.log(session.getId(),String.format("用户 %s 在终端 %s 登录", name, remoteIP==null?request.getRemoteAddr():remoteIP));
        }
        return "ok";
    }

    @GetMapping("/login")
    public String getLogin(HttpSession session) {
        if (session.getAttribute("login") == null) {
            return "index";
        }
        return "control";
    }

    @RequestMapping("/control")
    public String control(HttpSession session){
        if (session.getAttribute("login") == null) {
            return "index";
        }
        return "control";
    }

    /**
     * @return 各个接口对应区域的网络状态，状态不存在时返回"0"
     * @throws JsonProcessingException
     */
    @PostMapping(value = "/getstate")
    @ResponseBody
    public String getState() throws JsonProcessingException {
        return sshService.states.size()>0?mapper.writeValueAsString(sshService.states):"0";
    }

    /**
     * 重新连接交换机
     * @return 连接成功返回 "1"；失败返回"0"
     * @throws JsonProcessingException
     * @throws InterruptedException
     */
    @PostMapping("reConn")
    @ResponseBody
    public String reConn() throws JsonProcessingException{
        sshService.reconnect();
        if(sshService.states.size()>0){
            WebSessions.broad(mapper.writeValueAsString(sshService.states), null);
            return "1";
        }
        return "0";
    }

    /**
     * 改变指定房间的网络状态的控制器
     * 
     * @param room
     * @param state
     * @return "1" 开关正常 "0" 开关异常
     */
    @PostMapping("/togglestate")
    @ResponseBody
    public String toggle(@RequestParam String room, @RequestParam boolean state,@RequestParam int index,@RequestParam int delay,@RequestParam int duration,HttpSession session) {
        int i = 1;
        if(delay > 0){
            sshService.timeToToggle(room, delay, index, state);
        }else{
            i = sshService.toggle(room, state);
            WebSessions.broad(String.format("{\"index\":%d,\"state\":%b}",index,state),session.getId());
        }
        if(duration > 0){
            sshService.timeToToggle(room, delay + duration,index,!state);
        }
        sqlService.log(session.getId(),(delay==0?"":"延迟"+delay+"分钟 ") + (state?"开启":"关闭")+room+(duration==0?"":" "+duration+"分钟"));
        return "" + i;
    }

    /**
     * 开关所有接口的网络
     * @param open true：开，false：关
     * @param session
     * @return "1" 开关正常 "0" 开关异常
     */
    @PostMapping("/toggleAll")
    @ResponseBody
    public String toggleAll(@RequestParam boolean open,@RequestParam int delay,@RequestParam int duration, HttpSession session){
        int i = 1;
        if(delay > 0){
            sshService.timeToToggle(null, delay, -1,open);
        }else{
            i = sshService.doAll(open,session.getId());
        }
        if(duration > 0){
            sshService.timeToToggle(null, delay + duration, -1, !open);
        }
        sqlService.log(session.getId(), (delay==0?"":"延迟"+delay+"分钟 ")+ "全部" +(open?"开启":"关闭")+(duration==0?"":" "+duration+"分钟"));
        return "" + i;
    }

    /**
     * 用户注销
     */
    @RequestMapping("/logoff")
    @ResponseBody
    public String logoff(HttpSession session){
        session.invalidate();
        return "";
    }
    
    /**
     * 删除指定的计划任务
     * @param num
     * @return
     */
    @RequestMapping("/delTask")
    @ResponseBody
    public String delTask(@RequestParam String tm, HttpSession session){
        String task = sshService.delTask(tm);
        if(task != null) sqlService.log(session.getId(), "删除计划任务：" + task);
        return "";
    }

    @RequestMapping("/getTasks")
    @ResponseBody
    public String getTasks() throws JsonProcessingException{
        return mapper.writeValueAsString(sshService.getScheduledTasks());
    }
}